package com.example.elm.Account

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import com.example.elm.Public.AccountInfo
import com.example.elm.Public.MyApplication
import com.example.elm.databinding.RegisterBinding
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.io.StringReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import kotlin.concurrent.thread

class RegisterActivity : ComponentActivity() {
    private lateinit var binding: RegisterBinding
    private val server_ip = MyApplication.serverIp
    private val accountList = ArrayList<AccountInfo>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = RegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)
        GetAllAccount()

        binding.back.setOnClickListener {
            val intent = Intent()
            intent.putExtra("info",AccountInfo("", "", "", "", "", ""))
            setResult(RESULT_OK, intent)
            finish()
        }
        binding.registerButton.setOnClickListener {
            val people = binding.fullName.text.toString()
            val name = binding.username.text.toString()
            val phone = binding.phoneNumber.text.toString()
            val password = binding.password.text.toString()
            val password2 = binding.confirmPassword.text.toString()
            if (binding.phoneNumber.text.isNotEmpty()) {
                // 查询
                var phoneExists = false
                for (account in accountList) {
                    if (account.account == phone) {
                        phoneExists = true
                        break
                    }
                }
                if (phoneExists == true){
                    Toast.makeText(this, "该手机号已注册", Toast.LENGTH_SHORT).show()
                    binding.phoneNumber.text.clear()
                }

            }
            if (binding.fullName.text.isNotEmpty()) {
                // 进行数据库查询
                var people_nameExists = false
                for (account in accountList) {
                    if (account.people_name == people) {
                        people_nameExists = true
                        break
                    }
                }
                if (people_nameExists == true) {
                    Toast.makeText(this, "该姓名已注册", Toast.LENGTH_SHORT).show()
                    binding.fullName.text.clear()
                }
            }
            if(people.isEmpty())
                Toast.makeText(this, "姓名不可为空", Toast.LENGTH_SHORT).show()
            else if(phone.isEmpty())
                Toast.makeText(this, "电话号码不可为空", Toast.LENGTH_SHORT).show()
            else if(phone.length != 11)
                Toast.makeText(this, "电话号码格式不正确", Toast.LENGTH_SHORT).show()
            else if(name.isEmpty())
                Toast.makeText(this, "用户名不可为空", Toast.LENGTH_SHORT).show()
            else if(password.length < 8)
                Toast.makeText(this, "密码过短", Toast.LENGTH_SHORT).show()
            else if(password != password2)
                Toast.makeText(this, "两次密码不同", Toast.LENGTH_SHORT).show()
            else{
                val intent = Intent()
                intent.putExtra("info",AccountInfo(phone, password, name, people, "0", ""))
                setResult(RESULT_OK, intent)
                register(AccountInfo(phone, password, name, people, "0", ""))
                finish()
            }
        }
    }

    //连接服务器，加入新账号
    fun register(info: AccountInfo){
        val jsp = "http://$server_ip:8080/Account/add_Account.jsp"
        thread {
            var connection : HttpURLConnection? = null
            try {
                val response = StringBuilder()
                val url = URL(jsp)
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 8000 //  连接 超时
                connection.readTimeout = 8000 // read 超时时间
                connection.requestMethod = "POST"
                connection.setRequestProperty("Accept-Charset", "UTF-8")
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                val output = DataOutputStream(connection.outputStream)
                val paraStr = "&phone=${info.account}&password=${info.password}&name=${info.name}&people_name=${info.people_name}"
                output.write(paraStr.toByteArray())
                val input = connection.inputStream
                //  读取输入流，类似与文件流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use{
                    reader.forEachLine {
                        response.append(it)
                    }
                }
            }
            catch (e: Exception){
                e.printStackTrace()
            }
            finally {
                connection?.disconnect()
            }
        }
    }

    fun GetAllAccount(){
        val Account_all = "http://$server_ip:8080/Account/get_all_Account.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(Account_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (!responseData.isNullOrEmpty()) {
                    parseXml(responseData.toString().trim())
                } else {
                    Toast.makeText(this, "没有数据", Toast.LENGTH_LONG).show()
                }
            }
            catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            accountList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var phone = ""
            var password = ""
            var name = ""
            var people_name = ""
            var head_image = ""
            var introduction = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "phone" -> phone = xmlPullPaser.nextText()
                            "password" -> password = xmlPullPaser.nextText()
                            "name" -> name = xmlPullPaser.nextText()
                            "people_name" -> people_name = xmlPullPaser.nextText()
                            "head_image" -> head_image  = xmlPullPaser.nextText()
                            "introduction" -> introduction = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Account" == nodeName) {
                            accountList.add(AccountInfo(phone, password, name, people_name, head_image, introduction))
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }
}